<template>
  <div class='container'>
    <div class="userinfo">
      <img :src="userinfo.avatarUrl"
        alt=""
        class='avatar-img'>
      <p class="username">
        {{userinfo.nickName}}
        <button open-type="getUserInfo"
          lang="zh_CN"
          @getuserinfo="doLogin"
          class="getUserInfo"
          v-if='!userinfo.openId'>点击登录</button>
      </p>
    </div>
    <YearProgress></YearProgress>

    <button class='btn'
      @click="scanCode"
      v-if='userinfo.openId'>添加图书</button>
  </div>
</template>

<script>
import YearProgress from '@/components/YearProgress'
import qcloud from 'wafer2-client-sdk'
import config from '@/config'
import { showSuccess, post, showModal } from '@/util'
export default {
  data () {
    return {
      userinfo: {
        avatarUrl: '../../../static/img/unlogin.png',
        nickName: ''
      }
    }
  },
  onShow () {
    let userinfo = wx.getStorageSync('userInfo')
    if (userinfo) {
      this.userinfo = userinfo
    }
  },
  components: {
    YearProgress
  },
  methods: {
    doLogin () {
      let _self = this
      qcloud.setLoginUrl(config.loginUrl)
      qcloud.login({
        success: function (userInfo) {
          qcloud.request({
            url: config.userUrl,
            login: true,
            success: (userRes) => {
              showSuccess('登录成功')
              wx.setStorageSync('userInfo', userRes.data.data)
              _self.userinfo = userRes.data.data
            }
          })
        },
        fail: function (err) {
          console.log(err)
        }
      })
    },
    async addBook (isbn) {
      let _self = this
      const result = await post('/weapp/addbook', {
        isbn,
        openid: _self.userinfo.openId
      })

      showModal('添加成功', `${result.title}添加成功`)
    },
    scanCode () {
      let _self = this
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            _self.addBook(res.result)
            console.log(res.result)
          }
        }
      })
    }
  }
}
</script>

<style lang='scss'>
.container {
  padding: 0 30rpx;
  .userinfo {
    margin-top: 100rpx;
    text-align: center;
    .avatar-img {
      display: inline-block;
      width: 150rpx;
      height: 150rpx;
      margin: 20px;
      border-radius: 50%;
    }
    .username {
      margin-bottom: 20px;
    }
    .getUserInfo {
      display: block;
      width: 50%;
      height: 20px;
      line-height: 20px;
      font-size: 12px;
    }
  }
}
</style>
